from django.utils import timezone
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Agent, Workflow, WorkflowExecution
from .serializers import AgentSerializer, WorkflowSerializer, WorkflowExecutionSerializer
from .execution_engine import WorkflowExecutor


class AgentViewSet(viewsets.ModelViewSet):
    queryset = Agent.objects.all()
    serializer_class = AgentSerializer

    @action(detail=False, methods=['put'], url_path='bulk-update')
    def bulk_update(self, request):
        agents = request.data
        try:
            # 清空现有数据并批量创建
            Agent.objects.all().delete()
            created_agents = []
            for agent in agents:
                serializer = self.get_serializer(data=agent)
                serializer.is_valid(raise_exception=True)
                self.perform_create(serializer)
                created_agents.append(serializer.data)
            return Response(created_agents, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

class WorkflowViewSet(viewsets.ModelViewSet):
    queryset = Workflow.objects.all()
    serializer_class = WorkflowSerializer

    def perform_create(self, serializer):
        serializer.save()
    
    @action(detail=True, methods=['POST'])
    def execute(self, request, pk=None):
        """执行工作流接口"""
        workflow = self.get_object()
        execution = WorkflowExecution.objects.create(
            workflow=workflow,
            input_data=request.data,
            status='pending'
        )
        
        # 异步执行
        self.execute_workflow.delay(execution.id)
        
        return Response({
            'execution_id': execution.id,
            'status_url': f'/api/workflow-executions/{execution.id}/'
        }, status=202)

    @action(detail=True, methods=['GET'])
    def executions(self, request, pk=None):
        """获取执行记录"""
        workflow = self.get_object()
        executions = WorkflowExecution.objects.filter(workflow=workflow)
        serializer = WorkflowExecutionSerializer(executions, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['POST'])
    def execute_sync(self, request, pk=None):
        print('execute_sync:', request, pk, request.data)
        """同步执行工作流接口"""
        try:
           
            # 获取工作流
            print('aaaaa')
            workflow = self.get_object()
            print('bbbb')
            print("workflow", workflow)
            
            # 创建执行记录
            execution = WorkflowExecution.objects.create(
                workflow=workflow,
                input_data=request.data,
                status='running',
                started_at=timezone.now()
            )
            
            # 初始化执行引擎
            executor = WorkflowExecutor(workflow.id)
            executor.validate_workflow()
            
            # 执行工作流（同步）
            result = executor.execute_sync(execution.input_data)
            
            # 更新执行记录
            execution.output_data = result
            execution.status = 'completed'
            execution.completed_at = timezone.now()
            execution.save()
            print('response: ', {
                'status': 'completed',
                'result': result,
                'execution_id': execution.id})
            return Response({
                'status': 'completed',
                'result': result,
                'execution_id': execution.id,
                'execution_time': (execution.completed_at - execution.started_at).total_seconds()
            }, status=200)

        except Exception as e:
            print(str(e))
            # 错误处理
            # execution.status = 'failed'
            # execution.completed_at = timezone.now()
            # execution.output_data = {'error': str(e)}
            # execution.save()
            
            return Response({
                'status': 'failed',
                'error': str(e),
                'execution_id': execution.id if 'execution' in locals() else None
            }, status=500)

class WorkflowExecutionViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = WorkflowExecution.objects.all()
    serializer_class = WorkflowExecutionSerializer

    @action(detail=True, methods=['GET'])
    def status(self, request, pk=None):
        """获取执行状态"""
        execution = self.get_object()
        return Response({
            'status': execution.status,
            'result': execution.output_data if execution.status == 'completed' else None
        })